package com.tuoku.onepass

import android.content.Intent
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.widget.ImageView
import android.widget.TextView
import android.widget.Toast
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import com.tuoku.onepass.view.GestureLockView

class LoginGestureActivity : AppCompatActivity() {

    private lateinit var handler: Handler

    private lateinit var ivGoback: ImageView

    private lateinit var gestureLockView: GestureLockView

    private lateinit var tvGestureMsg: TextView

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContentView(R.layout.activity_login_gesture)
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets ->
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
            insets
        }

        initViews()

        setGobackListener()
        setGestureLockListener()

        handler = Handler(Looper.getMainLooper())
    }

    private fun initViews() {
        ivGoback = findViewById(R.id.iv_login_gesture_goback)
        gestureLockView = findViewById(R.id.gesture_lock_view)
        tvGestureMsg = findViewById(R.id.tv_gesture_msg)
    }

    private fun setGobackListener() {
        ivGoback.setOnClickListener { view ->
            // 跳转到LoginAccountActivity
            val intent = Intent(baseContext, LoginAccountActivity::class.java)
            startActivity(intent)
            finish()
        }
    }

    private fun setGestureLockListener() {
        gestureLockView.setOnGestureLockListener(object : GestureLockView.OnGestureLockListener {
            override fun onComplete(password: String) {
                // 验证手势密码
                if (password == "012345") { // 示例验证
                    // 跳转到MainActivity
                    val intent = Intent(baseContext, MainActivity::class.java)
                    startActivity(intent)
                    finish()
                } else {
                    Toast.makeText(baseContext, "密码错误", Toast.LENGTH_SHORT).show()
                    handler.postDelayed({
                        gestureLockView.reset()
                    }, 3000)
                }
            }

            override fun onStarted() {
                // 手势开始
            }

            override fun onError(message: String) {
                tvGestureMsg.text = message
            }
        })
    }
}